package com.example.demo.controller;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.Menu.MenuMapper;
import com.example.demo.pojo.Menu;


import com.example.demo.utility.AESUtils;
import com.example.demo.utility.CustomUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

/**
 * 菜单控制器
 *
 * @author yzh
 * @date 2022/12/20
 */
@Controller
public class MenuController extends BaseController {

    @Resource
    MenuMapper menuMapper;

    /**
     * 添加菜单
     *
     * @param menu 菜单
     */
    @RequestMapping("/addMenu")
    @ResponseBody
    public String addMenu(@RequestBody Menu menu) {
        String idKey = UUID.randomUUID().toString();

        menu.setIdKey(idKey);

        int insert = menuMapper.insert(menu);
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();

        long id = menuMapper.selectList(wrapper.eq("idKey", idKey)).get(0).getId();
        JSONObject json = new JSONObject(new LinkedHashMap());
        json.put("flag", insert);
        json.put("id", id);

        return json.toString();

    }


    /**
     * 删除菜单
     *
     * @return {@link String}
     */
    @RequestMapping("/deleteMenu")
    @ResponseBody
    public String deleteMenu(String id) {

        int i = menuMapper.deleteById(id);
        if (i == 1) {
            System.out.println("菜单删除了id为" + id + "的数据");
        } else {
            System.out.println("菜单id为" + id + "的数据删除失败");
        }
        return "1";

    }

    /**
     * 获取菜单,渲染菜单用
     *
     * @return
     */
    @RequestMapping("/getMenu")
    @ResponseBody
    public String getMenu() {
        //用HttpServletResponse res返回json时这么写
        /*res.setHeader("Content-type", "application/json;charset=UTF-8");
        res.setCharacterEncoding("UTF-8");*/
        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        //获取一级菜单数据
        List<Menu> list = menuMapper.selectList(wrapper.eq("tag", "0").orderByAsc("level_id"));


        JSONArray menuJson = new JSONArray();

        //遍历一级菜单
        for (int i = 0; i < list.size(); i++) {
            Menu menu = list.get(i);

            //LinkedHashMap是为了让它按put的先后顺序排序
            JSONObject first = new JSONObject(new LinkedHashMap<>());

            first.put("path", menu.getPath());
            first.put("title", menu.getTitle());


            JSONArray jsonArray = new JSONArray();
            //获取这个一级菜单下的二级菜单
            List<Menu> byTag = menuMapper.selectByTag(menu.getId());
            //遍历获得二级菜单，先存入jsonArray
            for (int j = 0; j < byTag.size(); j++) {

                Menu menu1 = byTag.get(j);
                JSONObject second = new JSONObject();
                second.put("path", menu1.getPath());
                second.put("title", menu1.getTitle());

                jsonArray.add(second);
            }
            //将二级菜单和一级菜单拼接
            first.put("children", jsonArray);

            //再将这个模块菜单一个整体存入menujson
            menuJson.add(first);
        }
        //用HttpServletResponse res返回json时这么写
        /*res.getWriter().write(menuJson.toString());*/
        return menuJson.toString();
    }


    /**
     * 获取菜单配置
     *
     * @return {@link String}
     */
    @RequestMapping("/getMenu_config")
    @ResponseBody
    public String getMenu_config() {
        //用HttpServletResponse res返回json时这么写
        /*res.setHeader("Content-type", "application/json;charset=UTF-8");
        res.setCharacterEncoding("UTF-8");*/

        QueryWrapper<Menu> wrapper = new QueryWrapper<>();
        //获取一级菜单数据
        List<Menu> list = menuMapper.selectList(wrapper.eq("tag", "0").orderByAsc("level_id"));

        List<Integer> list1 = menuMapper.selectLevels();
        Integer maxlevel = list1.stream().max(Integer::compare).get();


        JSONObject json = new JSONObject(new LinkedHashMap<>());

        JSONArray menuJson = new JSONArray();

        //遍历一级菜单
        for (int i = 0; i < list.size(); i++) {
            Menu menu = list.get(i);

            //LinkedHashMap是为了让它按put的先后顺序排序
            JSONObject first = new JSONObject(new LinkedHashMap<>());

            first.put("id", menu.getLevel_id());
            first.put("label", menu.getTitle());
            first.put("idKey", menu.getId());


            JSONArray jsonArray = new JSONArray();
            //获取这个一级菜单下的二级菜单
            List<Menu> byTag = menuMapper.selectByTag(menu.getId());
            //遍历获得二级菜单，先存入jsonArray
            for (int j = 0; j < byTag.size(); j++) {

                Menu menu1 = byTag.get(j);
                JSONObject second = new JSONObject();
                second.put("id", menu1.getLevel_id());
                second.put("label", menu1.getTitle());
                second.put("idKey", menu1.getId());

                jsonArray.add(second);
            }
            //将二级菜单和一级菜单拼接
            first.put("children", jsonArray);

            //再将这个模块菜单一个整体存入menujson
            menuJson.add(first);
        }
        json.put("menu", menuJson);
        json.put("maxlevel", maxlevel);
        //用HttpServletResponse res返回json时这么写
        /*res.getWriter().write(menuJson.toString());*/
        return json.toString();
    }


    /**
     * 位置变换时保存菜单
     */
    @RequestMapping("/update_menu")
    @ResponseBody
    public void update_menu(HttpServletRequest request) {
        String json = request.getParameter("json");
        Long parent_id = Long.valueOf((request.getParameter("parent_id")));

        int i = 0;

        JSONArray array = JSON.parseArray(json);//将string型的json转成可遍历的数组

        for (Object obj : array) {
            Menu menu = new Menu();
            JSONObject jsonObject = JSON.parseObject(obj.toString());

            menu.setId(jsonObject.getInteger("idKey"));
            menu.setLevel_id(jsonObject.getInteger("id"));
            if (parent_id != 0) {
                menu.setTag(parent_id);
            }
            i = menuMapper.updateById(menu);
        }

        if (i == 1) {
            System.out.println("菜单修改成功");
        } else {
            System.out.println("菜单修改失败");
        }

    }

    @RequestMapping("/Test")
    @ResponseBody
    public void Test() throws Exception {
        StringBuffer request_all = CustomUtil.get_request_all();
        System.out.println(request_all);
        String s = getPara("json");
        System.out.println(s);
        String s1 = AESUtils.aesDecrypt(s);
        System.out.println(s1);

    }

    /**
     * @author yzh
     * @time 2023/6/6
     * 查询id的信息
     */
    @RequestMapping("/select_menuid")
    @ResponseBody
    public Menu select_menuid() {
        String id = getPara("id");
        System.out.println(id);
        Menu menu = menuMapper.selectById(id);
        return menu;

    }

    /**
     * 修改菜单模块信息
     */
    @RequestMapping("/update_menu_information")
    @ResponseBody
    public String update_menu_information(@RequestBody Menu menu) {
        menuMapper.updateById(menu);
        return "1";

    }
}
